package com.commit.controller;

import com.commit.domain.Answer;
import com.commit.domain.Question;
import com.commit.service.AnsService;
import com.commit.service.QuestionService;
import com.commit.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author:zyh
 * @Time:2021-02-28-9:47
 * @email:1269231889@qq.com
 */
@Controller
@Api(value = "问题接口")
@RequestMapping("/ques")
public class QuestionController {
    @Autowired
    private AnsService ansService;
    @Autowired
    private UserService userService;
    @Autowired
    private QuestionService questionService;
    @GetMapping("/form")
    public String form(){
        return "questionForm";
    }
    @RequestMapping("/save")
    public String save(Question ques, HttpSession session){
        questionService.save(ques,session);
        return "redirect:/index";
    }
    //问题详细
    @RequestMapping("/detail")
    public String detail(Integer id, Model model){
        Question ques = questionService.findById(id);
        List<Answer> answers = ansService.findByQuesId(id);
        String username = userService.findById(ques.getUserId()).getUsername();
        model.addAttribute("username",username);
        model.addAttribute("question",ques);
        model.addAttribute("answerList",answers);
        return "questionDetail";
    }
    //置顶
    @ResponseBody
    @RequestMapping("/toTop")
    public String toTop(Question question){
        questionService.update(question);
        return "success";
    }
    // 删除
    @ResponseBody
    @DeleteMapping("/del/{id}")
    public String del(@PathVariable("id")Integer id){
        questionService.del(id);
        return  "success";
    }

    @GetMapping("/searchTitle")
    @ApiImplicitParam(name = "title",value = "问题",required = true,paramType = "query")
    public HttpEntity<String> findByTitle(@RequestParam("title") String title){
        try {
            List<Question> byTitle = questionService.findByTitle(title);
            return  ResponseEntity
                    .ok()
                    .body(byTitle.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity
                    .status(404)
                    .body("没有找对问题");
        }
    }
}
